// import CryptoJS from 'crypto-js'
// import { system_config } from './_config.js'
/**
 * @description: 校验表单参数是否符合校验规则
 * @param {*} params 【Object】需校验的参数
 * @param {*} rules 【Array】校验规则 
 * { require: 是否必填, variable: 校验参数名称, message: 校验失败的返回信息, reg: 校验正则 }
 * @return {*}
 */
export const verificationParams = (params, rules) => {
	let paramsKeys = Object.keys(params),
		verificaNum = 0
	for (let rule in rules) {
		let ruleItem = rules[rule]
		if (ruleItem.require && paramsKeys.includes(ruleItem.variable) && params[ruleItem.variable]) {
			if (ruleItem.reg) {
				if (ruleItem.reg.test(params[ruleItem.variable])) verificaNum++
				else {
					showToastMsg(ruleItem.message)
					return {
						status: false,
						params
					}
				}
			} else verificaNum++
		} else {
			showToastMsg(ruleItem.message)
			return {
				status: false,
				params
			}
		}
	}
	if (verificaNum == rules.length) return {
		status: true,
		params
	}
}
//消息提示
export const showToastMsg = (title, time) => {
	uni.showToast({
		icon: 'none',
		title,
		duration: time || 1500
	})
}
//消息提示
export const showModalMsg = (title, comtent, callBack) => {
	uni.showModal({
		title: title || '提示',
		content: comtent || '这是一个模态弹窗',
		success: function(res) {
			if (res.confirm) {
				callBack(true)
				console.log('用户点击确定');
			} else if (res.cancel) {
				callBack(false)
				console.log('用户点击取消');
			}
		}
	})
}
/**
 * @description: 时间转换
 * @param {*} type 【String】转换类型
 * @param {*} value 【Date】 日期转时间戳时的传参，
 * 	类型【yyyy/MM/dd hh:mm:ss，yyyy/MM/dd，yyyy,mth,dd】
 * @return {*}
 */
export const timeTransfer = (type = 'timestampToDate', value) => {
	let date = value ? new Date(value) : new Date(),
		time = ''
	switch (type) {
		case 'timestampToDate':
			let Y = date.getFullYear() + '-';
			let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
			let D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
			let h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
			let m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes()) + ':';
			let s = date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds()
			time = Y + M + D + h + m + s
			break
		case 'dateToTimestamp':
			time = new Date(value).getTime()
			break
		case 'timeToTimestamp':
			if (typeof value == 'number') return value
			else if (typeof value == 'string') {
				// 2022-08-23 13:22:22 or 2022-08-23
				const _split = value.split(' ')
				let Y, M, D, h, m, s
				const _data = _split[0].split('-')
				Y = _data[0];
				M = Number(_data[1]) - 1;
				D = _data[2]
				if (_split.length > 1) {
					const _time = _split[1].split(':')
					h = _time[0];
					m = _time[1];
					s = _time[2]
				}
				return new Date(Y, M, D, h, m, s).getTime()
			}
			break
		case 'timeToWeek':
			let dayArr = {
				1: '一',
				2: '二',
				3: '三',
				4: '四',
				5: '五',
				6: '六',
				0: '日'
			}
			time = '星期' + dayArr[new Date().getDay()]
			break
		default:
			break
	}
	return time
}
/**
 * @description: 文本复制
 * @param {*} content 【String】复制的文本
 * @param {*} success 【Function】 调用成功方法
 * @param {*} error 【Function】 调用失败方法
 * @return {*}
 */
export const uniCopy = ({
	content,
	success,
	error
}) => {
	if (!content) return error('复制的内容不能为空 !')
	content = typeof content === 'string' ? content : content.toString() // 复制内容，必须字符串，数字需要转换为字符串
	/**
	 * 小程序端 和 app端的复制逻辑
	 */
	//#ifndef H5
	uni.setClipboardData({
		data: content,
		success: function() {
			success("复制成功~")
		},
		fail: function() {
			success("复制失败~")
		}
	});
	//#endif

	/**
	 * H5端的复制逻辑
	 */
	// #ifdef H5
	if (!document.queryCommandSupported('copy')) {
		//为了兼容有些浏览器 queryCommandSupported 的判断
		// 不支持
		error('浏览器不支持')
	}
	let textarea = document.createElement("textarea")
	textarea.value = content
	textarea.readOnly = "readOnly"
	document.body.appendChild(textarea)
	textarea.select() // 选择对象
	textarea.setSelectionRange(0, content.length) //核心
	let result = document.execCommand("copy") // 执行浏览器复制命令
	if (result) success("复制成功~")
	else error("复制失败，请检查h5中调用该方法的方式，是不是用户点击的方式调用的，如果不是请改为用户点击的方式触发该方法，因为h5中安全性，不能js直接调用！")
	textarea.remove()
	// #endif
}
/**
 * @description: 返回上一页面传参
 * @param {*} paramsKey 传递的参数key值
 * @param {*} params 传递的参数value值
 * @param {*} type 【String】 前一页/后一页[before/after]
 * @return {*}
 */
export const backPageParams = (paramsKey, params, type, skipType, str, specital) => {
	let pages = getCurrentPages()
	if (type == 'after') {
		let prevPage = pages[pages.length - 2]
		// #ifndef MP-WEIXIN
		prevPage.$vm[paramsKey] = params
		// #endif
		// #ifdef MP-WEIXIN
		prevPage.setData({
			[paramsKey]: params
		})
		// #endif
		if (skipType) skipType()
		else uni.navigateBack({
			delta: 1
		})
	} else if (type == 'before') {
		let currPage = pages[pages.length - 1]
		// #ifndef MP-WEIXIN
		return currPage.$vm?.[paramsKey] ?? ''
		// #endif
		return currPage.data?.[paramsKey] ?? ''
	}
}
/**
 * @description: 缓存 设置过期时间,默认有效期1天
 * @param {key}  失效时间标识属性
 * @param {value}  失效时间标识值
 * @param {seconds}  失效秒数 10分钟
 * @return {*}
 */
export const cacheAndSetDeadTime = (key, value, seconds) => {
	
	let timestamp = Date.parse(new Date()) / 1000
	if (key && value === null) {
		//删除缓存
		//获取缓存
		let val = uni.getStorageSync(key);
		let tmp = val.split("|")
		if (!tmp[1] || timestamp >= tmp[1]) {
			uni.removeStorageSync(key)
			return ""
		} else {
			return tmp[0]
		}
	} else if (key && value) {
		//设置缓存 默认有效期1天
		let expire = timestamp + (3600 * 24)
		if (!seconds) {
			expire = timestamp + (3600 * 24)
		} else {
			expire = timestamp + seconds
		}
		value = value + "|" + expire
		uni.setStorageSync(key, value);
	} else {
		console.log("key不能空")
	}
}
/**
 * @description: 判断设备系统
 * @return {*} 设备是否为Android
 */
export const devicesIsAndroid = () => {
	const res = uni.getSystemInfoSync()
	const platform = res.platform
	return (platform == 'android')
}
/**
 * @description: Android录屏配置
 * @param {event}  返回值
 * @param {cb}  回调函数
 */
export const ScreenRecorderAndroidCallback = (_this, event, cb) => {
	if (event.code == 201) {
		console.log("开始录制")
	} else if (event.code == 202) {
		console.log("录制中")
	} else if (event.code == 203) {
		console.log("点击悬浮窗回到应用")
		uni.showModal({
			content: _this.$t('taskDetail.offRecording'),
			success(_res) {
				if (_res.confirm) {
					_this.offRecord()
				}
			}
		})
	} else if (event.code == 200) {
		console.log("录制结束")
		cb && cb(event)
	}
}
/**
 * @description: Ios录屏回调
 * @param {type}  返回值
 * @param {cb}  回调函数
 */
export const ScreenRecorderV2CallBack = (_this, {
	tips,
	type,
	filePath
}, cb) => {
	if (type == "broadcastStarted") {
		console.log("录屏开始");
	} else if (type == "broadcastPaused") {
		console.log("录屏暂停");
	} else if (type == "broadcastResumed") {
		console.log("录屏继续");
	} else if (type == "broadcastFinished") {
		console.log("录屏完成");
	} else if (type == "startExportVideo") {
		uni.showLoading({
			title: tips
		})
	} else if (type == "endExportVideo") {
		uni.hideLoading()
		uni.saveImageToPhotosAlbum({
			filePath: plus.io.convertAbsoluteFileSystem(filePath),
			success: function() {
				cb && cb()
			},
			fail: function(e) {
				console.log(JSON.stringify(e));
			}
		})
	}
}
/**
 * @description: 点击推送消息回调
 * @param _this 【Object: this对象】
 * @param message 【Object: 消息对象】
 */
export const _handlePush = (_this, message) => {
	console.log(message)
	const _payload = message.payload
	if (_payload.type == 'screen') {
		let retInfo = null
		cropVideo(_payload.filePath, _this, (ret) => {
			_this.save_entryInfo({
				entry_id: '',
				level: 2,
				localFile: {
					path: ret.mp4,
					duration: ret.duration,
					size: ret.size
				},
				resource: ret.mp4,
				fileType: 'video',
				content: '',
				poster: ret.image,
				taskId: uni.getStorageSync('entry_id_remove')
			})
		})
		setTimeout(() => {
			uni.navigateTo({
				url: "/pages/entryDetail/index?type=add"
			})
		}, 1000)
	} else if (_payload.type == 'comment') {
		let pages = getCurrentPages()
		// let currentRouter = pages[pages.length - 1].route
		// console.log(currentRouter,'pages')
		// if(currentRouter === 'pages/notice/index') this.$router.go(0)
		uni.setStorageSync('_payload', _payload)
		uni.switchTab({
			url: "/pages/notice/index?id=1"
		})
	} else if (_payload.type == 'remind') {
		uni.setStorageSync('_payload', _payload)
		uni.switchTab({
			url: "/pages/notice/index"
		})
	}
}
/**
 * @description: 监听推送消息回调
 * @param _this 【Object: this对象】
 * @param message 【Object: 消息对象】
 * @param platform 【String: 设备信息】
 */
// export const _receivePush = (_this,message,platform) => {
// 	if (message.payload&&message.payload.loc){
// 		const loc = JSON.parse(message.payload.loc)
// 		if (loc['TYPE'] == 'partner-commented-entry') {
// 			plus.push.createMessage(message.payload.body, {type: 'comment',entry_id: loc['ENTRY_ID'],comment_id: loc['COMMENT_ID']},{
// 				title: message.payload.title,
// 				cover: false,
// 				sound: 'system'
// 			})
// 		} else if(loc['TYPE'] == 'Digcore remind'){
// 			plus.push.createMessage(message.payload.body, {type: 'remind'},{
// 				title: message.payload.title,
// 				cover: false,
// 				sound: 'system'
// 			})
// 		}
// 	}
// }
/**
 * @description: 参数解密
 * @param ciphertext 【String: 加密后的传参】
 * @return {*}  解密后的源数据
 */
export const paramsDecrypt = (ciphertext) => {
	const base64 = CryptoJS.enc.Base64.parse(ciphertext)
	const bytes = CryptoJS.AES.decrypt(base64.toString(CryptoJS.enc.Utf8), system_config.secretKey)
	const originalText = JSON.parse(bytes.toString(CryptoJS.enc.Utf8))
	return originalText
}
/**
 * @description: 参数加密
 * @param params 【Any: 接口响应 Json字符串】
 * @return {*}  加密后的源数据
 */
export const responseEncrypt = (params) => {
	const bytes = CryptoJS.AES.encrypt(params, system_config.secretKey).toString()
	return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(bytes))
}
/**
 * @description: 兼容不同尺寸
 * @param data 【Object: 资源信息】
 * @param type 【String: 获取资源类型】
 * @return {*}  加密后的源数据
 */
export const getPVsize = (data, type) => {
	const _data = {
		...data
	}
	const _data_size = Object.keys(data.size)
	delete _data.size
	Object.keys(_data).map(_d => {
		if (!_data_size.includes(_d)) delete _data[_d]
	})
	if (type == 'sizeW') {
		if (_data.normal) return data.size.normal.w
		else if (_data.fullviewstandard) return data.size.fullviewstandard.w
		else if (_data.large) return data.size.large.w
		else if (_data.fullviewretina) return data.size.fullviewretina.w
		else if (_data.timelineretina) return data.size.timelineretina.w
		else if (_data.timelinestandard) return data.size.timelinestandard.w
		else if (_data.small) return data.size.small.w
		else if (_data.medium) return data.size.medium.w
		else if (_data.mmedium) return data.size.mmedium.w
		else if (_data.msmall) return data.size.msmall.w
		else return 450
	} else if (type == 'sizeH') {
		if (_data.normal) return data.size.normal.h
		else if (_data.fullviewstandard) return data.size.fullviewstandard.h
		else if (_data.large) return data.size.large.h
		else if (_data.fullviewretina) return data.size.fullviewretina.h
		else if (_data.timelineretina) return data.size.timelineretina.h
		else if (_data.timelinestandard) return data.size.timelinestandard.h
		else if (_data.small) return data.size.small.h
		else if (_data.medium) return data.size.medium.h
		else if (_data.mmedium) return data.size.mmedium.h
		else if (_data.msmall) return data.size.msmall.h
		else return 450
	} else {
		if (_data.normal) return data.normal
		else if (_data.fullviewstandard) return data.fullviewstandard
		else if (_data.large) return data.large
		else if (_data.fullviewretina) return data.fullviewretina
		else if (_data.timelineretina) return data.timelineretina
		else if (_data.timelinestandard) return data.timelinestandard
		else if (_data.small) return data.small
		else if (_data.medium) return data.medium
		else if (_data.mmedium) return data.mmedium
		else if (_data.msmall) return data.msmall
		// else return {state:'local', img: noThumbnailFile}
	}
}
/**
 * @description: 视频裁剪的视频时长是否超限制
 * @param ret 【Object: 视频的信息】
 * @param cb 【_this: this对象】
 */
export const compareTime = (_this) => {
	let title = _this.$t('upload.tips')
	const video_max_length = uni.getStorageSync('video_max_length'),
		locale = _this.$i18n.locale
	const _timeNum = video_max_length / 60
	if (locale === 'en') {
		title = title.replace('{TIME}', _timeNum)
		title = title.replace('{UNIT}', _timeNum > 1 ? 's' : '')
	} else title = title.replace('{TIME}', _timeNum)
	return title
}
/**
 * @description: 视频裁剪
 * @param path 【String: 视频的绝对路径】
 * @param cb 【Function: 回调函数】
 */
export const cropVideo = (path, _this, cb) => {
	const _cropVideo = uni.requireNativePlugin("Html5app-VideoCrop")
	let title = compareTime(_this)
	_cropVideo.openCrop({
		"url": path,
		"resolution": "480p",
		"mode": "fill",
		"quality": "sd",
		"codecs": 2,
		"mintime": 1000,
		"maxtime": uni.getStorageSync('video_max_length'),
		"maxTimeTip": title,
		"gop": "5",
		"fps": "25",
		"saveToAlbum": false
	}, ret => {
		console.log(JSON.stringify(ret));
		if (ret.code == "0") {
			_this.save_cropVideoObj(_cropVideo)
			cb && cb(ret, _cropVideo)
		}
	});
}

// 上传视频
export const chooseVideo = async () => {
	uni.showLoading({
		mask: true,
		title: '上传中...'
	})
	// uploadFile 存储需要上传的文件
	let uploadFile = ''
	// 1.选择要上传的视频
	const res = await uni.chooseVideo({
		maxDuration: 60, // 拍摄视频最长拍摄时间，单位秒。最长支持 60 秒。
		sourceType: ['album'], // album 从相册选视频，camera 使用相机拍摄，默认为：['album', 'camera']
	});
	uploadFile = res[1].tempFilePath;
	// console.log(uploadFile);
	var that2 = this;
	// 2.上传所选视频到服务器
	const arr = await uni.uploadFile({
		// 需要上传的地址
		url: that2.vuex_uploadAction,
		// filePath  需要上传的文件
		filePath: uploadFile,
		name: 'file',
		header: {
			token: that2.vuex_token // 挂载请求头为用户的 token
		},
	});
	let data = JSON.parse(arr[1].data)
	console.log('data:', data);
	if (data.code !== 1) { // 视频上传失败了
		uni.hideLoading()
		return
	}
	// 上传成功(把上传成功后的文件路径 push 到页面需要显示的视频数据列表中)
	that2.uploadVideoUrl = data.data.fullurl
	that2.formData.video_url = data.data.url
	uni.hideLoading()
}

//敏感词判断


//优化时间 去除空格
export const getUploadDate = (date) => {
	if (!date) return
	if (date.indexOf(" ") == "-1") return date
	let arr = date.split(" ")
	return arr[0]
};


/**
 * @description: 是否为数组
 * @param {*} value
 * @return {*}
 */
export const isArray = (value) => {
	return Object.prototype.toString.call(value) === "[object Array]"
}

/**
 * @description: 获取后缀名
 * @param {*} v
 * @return {*}
 */
export const getSuffix = (v) => {
	return v.match(/\.([^.]+)$/)[1];
}
/**
 * @description: 字节转换
 * @param {*} limit
 * @return {*} size 
 */
// toFixed(2) 四舍五入 2是保留的小数
export const formatSize = (limit) => {
	if (!limit || Number(limit) == 0) return ''
	limit = Number(limit)
	// 将size B转换成 M
	var size = ''
	if (limit < 1 * 1024) {
		//小于1KB，则转化成B
		size = limit.toFixed(2) + 'B'
	} else if (limit < 1 * 1024 * 1024) {
		//小于1MB，则转化成KB
		size = (limit / 1024).toFixed(2) + 'KB'
	} else if (limit < 1 * 1024 * 1024 * 1024) {
		//小于1GB，则转化成MB
		size = (limit / (1024 * 1024)).toFixed(2) + 'MB'
	} else {
		//其他转化成GB
		size = (limit / (1024 * 1024 * 1024)).toFixed(2) + 'GB'
	}

	var sizeStr = size + '' //转成字符串
	var index = sizeStr.indexOf('.') //获取小数点处的索引
	var dou = sizeStr.substr(index + 1, 2) //获取小数点后两位的值
	if (dou == '00') {
		//判断后两位是否为00，如果是则删除00
		return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
	}
	return size
}